//
//  DTListVC.m
//  DTDemo
//
//  Created by gan on 2018/6/4.
//  Copyright © 2018年 斑马旅游. All rights reserved.
//

#import "DTListVC.h"
#import <DTCoreText/DTCoreText.h>
#import <DTFoundation/DTFoundation.h>
#import "ZSDTCoreTextCell.h"
#import "ZSDTLazyImageView.h"
#import "ZSDTCoreTextButton.h"

@interface DTListVC ()<UITableViewDataSource,UITableViewDelegate,DTAttributedTextContentViewDelegate,DTLazyImageViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong,nonatomic)NSMutableArray* list;
//类似tabelView的缓冲池，用于存放图片大小
@property (nonatomic, strong) NSCache *imageSizeCache;
@property (nonatomic,strong)NSCache *cellCache;


@property (nonatomic,assign)BOOL isScrolling;

@end

@implementation DTListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"DTList";
    self.view.backgroundColor = [UIColor whiteColor];

    self.imageSizeCache = [[NSCache alloc]init];
    self.cellCache = [[NSCache alloc]init];
    self.list = [NSMutableArray array];
    [self initData];
    
}

-(void)initData
{

    NSString* str0 = @"<p><span style=\"color: rgb(255, 0, 0);\"><strong>5月12日及之前出发的团期为您安排的是大自然餐厅；</strong></span></p><p><span style=\"color: rgb(255, 0, 0);\"><strong>5月13日及之后出发的团期为您安排的是普吉山顶餐厅。</strong></span></p><p><img title=\"product_5a40d3b35816a.jpg\" alt=\"\" src=\"https://oi3v1wa3b.qnssl.com/product_5a40d3b35816a.jpg\"/><img title=\"product_5a40d3b701d45.jpg\" alt=\"\" src=\"https://oi3v1wa3b.qnssl.com/product_5a40d3b701d45.jpg\"/><img title=\"product_5a40d3bca3d94.jpg\" alt=\"\" src=\"https://oi3v1wa3b.qnssl.com/product_5a40d3bca3d94.jpg\"/><img title=\"product_5a40d3c8a6198.jpg\" alt=\"\" src=\"https://oi3v1wa3b.qnssl.com/product_5a40d3c8a6198.jpg\"/><img title=\"product_5a40d3d00b6a5.jpg\" alt=\"\" src=\"https://oi3v1wa3b.qnssl.com/product_5a40d3d00b6a5.jpg\"/><img title=\"product_5a40d3f705844.jpg\" alt=\"\" src=\"https://oi3v1wa3b.qnssl.com/product_5a40d3f705844.jpg\"/><br/></p>";
    [self.list addObject:str0];

}

- (IBAction)btnReload:(id)sender {
}


#pragma mark - UITableViewDelegate
//返回组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.list.count;
}
//返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
//返回单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:{
            //普通单元格
            UITableViewCell* cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.textLabel.text = [NSString stringWithFormat:@"Index:%ld",indexPath.section];
            return cell;
            break;
        }
        case 1:{
            //富文本单元格
            //自定义方法，创建富文本单元格
            ZSDTCoreTextCell *cell = (ZSDTCoreTextCell *)[self coreTextCellWithIndexPath:indexPath];
            return cell;
            break;
        }
        default:
            break;
    }
    return nil;
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:{
            return 44;
            break;
        }
        case 1:{
            ZSDTCoreTextCell *cell = (ZSDTCoreTextCell *)[self coreTextCellWithIndexPath:indexPath];
            CGFloat hei = [cell requiredRowHeightInTableView:tableView];
            NSLog(@"rowHei-section:%ld  hei:%.2f",indexPath.section,hei);
            return hei;
            break;
        }
        default:
            break;
    }
    return 0;
}


-(ZSDTCoreTextCell*)coreTextCellWithIndexPath:(NSIndexPath*)indexPath
{
    NSString *key = [NSString stringWithFormat:@"DTCoreTextCellKEY%ld-%ld", (long)indexPath.section, (long)indexPath.row];
    NSLog(@"key:%@",key);
    ZSDTCoreTextCell *cell = [self.cellCache objectForKey:key];
    if (!cell){
        cell = [[ZSDTCoreTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DTCoreTextCell"];
        cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.hasFixedRowHeight = YES;
        cell.textDelegate = self;
        cell.attributedTextContextView.shouldDrawImages = YES;
        //记录在缓存中
        [self.cellCache setObject:cell forKey:key];
    }
    //2.设置数据
    //2.1为富文本单元格设置Html数据
    NSString* html = [self.list objectAtIndex:indexPath.section];
    [cell setHTMLString:html];
    //            [cell setHTMLString:self.dataSource[indexPath.section][indexPath.row]];
    //2.2为每个占位图(图片)设置大小，并更新
    for (DTTextAttachment *oneAttachment in cell.attributedTextContextView.layoutFrame.textAttachments) {
        NSValue *sizeValue = [self.imageSizeCache objectForKey:oneAttachment.contentURL];
        if (sizeValue) {
            cell.attributedTextContextView.layouter=nil;
            oneAttachment.displaySize = [sizeValue CGSizeValue];
            [cell.attributedTextContextView relayoutText];
        }
    }
    [cell.attributedTextContextView relayoutText];
    return cell;
    
}



#pragma mark - DTAttributedTextContentViewDelegate
//对于没有在Html标签里设置宽高的图片，在这里为其设置占位
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    if([attachment isKindOfClass:[DTImageTextAttachment class]]){
        ZSDTLazyImageView *imageView = [[ZSDTLazyImageView alloc] initWithFrame:frame];
        imageView.delegate = self;
        imageView.image = [(DTImageTextAttachment *)attachment image];
        imageView.textContentView = attributedTextContentView;
        imageView.url = attachment.contentURL;
        return imageView;
    }
    return nil;
}


//对于无宽高懒加载得到的图片，缓存记录其大小,然后执行表视图更新
- (void)lazyImageView:(ZSDTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size{
    BOOL needUpdate = NO;
    NSURL *url = lazyImageView.url;
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
    /* update all attachments that matchin this URL (possibly multiple
     images with same size)
     */
    for (DTTextAttachment *oneAttachment in [lazyImageView.textContentView.layoutFrame textAttachmentsWithPredicate:pred]){
        // update attachments that have no original size, that also sets the display size
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero)){
            oneAttachment.originalSize = size;
            NSValue *sizeValue = [self.imageSizeCache objectForKey:oneAttachment.contentURL];
            if (!sizeValue) {
                //将图片大小记录在缓存中，但是这种图片的原始尺寸可能很大，所以这里设置图片的最大宽
                //并且计算高
                CGFloat aspectRatio = size.height / size.width;
                CGFloat width = ZSToolScreenWidth - 15*2;
                CGFloat height = width * aspectRatio;
                CGSize newSize = CGSizeMake(width, height);
                [self.imageSizeCache setObject:[NSValue valueWithCGSize:newSize]forKey:url];
                NSLog(@"url:%@ hei:%.2f",url,height);
            }
            needUpdate = YES;
        }
    }
    
    if (needUpdate){
        //有新的图片尺寸被缓存记录的时候，需要刷新表视图
        //[self reloadCurrentCell];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadCurrentCell) object:nil];
        self.isScrolling = NO;
        [self performSelector:@selector(reloadCurrentCell) withObject:nil afterDelay:0.2];
    }
}

- (void)reloadCurrentCell{
    //如果当前表视图在滑动就不执行刷新，因为滑动时候会自动调用表视图的刷新方法
    if (self.isScrolling) {
        return;
    }
    //如果当前表视图没有在滑动，就手动刷新当前在屏幕显示的单元格
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    if(indexPaths){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
        });
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _isScrolling = YES;
}

//显示动画，表视图停止滑动之后调用；没有动画此方法不调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    _isScrolling = NO;
       [self reloadCurrentCell];
}

//手指拖动表视图，表视图停止滑动之后调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    _isScrolling = NO;
        [self reloadCurrentCell];
}



- (void)dealloc{
    NSLog(@"dealloc-%@",self);
}

@end
